<?php

// +----------------------------------------------------------------------
// |公共接口服务层
// +----------------------------------------------------------------------

namespace app\Api\system;

use think\facade\Validate;
use think\facade\Db;
use think\facade\Cache;
use app\common\Model\ConfigModel;

class CommonsService
{  

  //dh.base.measures.get$1.0 (获取单位列表接口)
    public  static function getMeasures($accessToken){
        $method='dh.base.measures.get';
        $sysParams = [
            'method' => $method,
            'v' => '1.0',
            'access_token' => $accessToken,
            'timestamp' => round(microtime(true) * 1000),            
        ];
        $res=crul($sysParams); 
         $data=[];
        if($res['meauserList']){
            foreach ($res['meauserList'] as $v) {
                   $data[]=[
                        'valid'=>$v['valid'],//是否有效（1：是， 0：不是）
                        'shortname'=>$v['shortname'],// 名称缩写
                        'cname'=>$v['cname'],//中文名
                        'plural'=>$v['plural'],//名称(复数)                
                        'measureid'=>$v['measureid'],//主键ID
                        'name'=>$v['name'],//名称
                        'description'=>$v['description'],//主描述
                    ];
            }
        }
         if($data){
          Db::name('measures')->insertAll($data);
          return '数据插入成功';
        }else{
          return '数据插入失败'; 
        } 
    }

  ////dh.base.countrys.get$1.0 (获取国家列表接口)
    public  static function getCountrys($accessToken){
        $method='dh.base.countrys.get';
        $sysParams = [
            'method' => $method,
            'v' => '1.0',
            'access_token' => $accessToken,
            'timestamp' => round(microtime(true) * 1000),            
        ];
        $res=crul($sysParams); 
         $data=[];
        if($res['countryList']){
            foreach ($res['countryList'] as $v) {
                $data[]=[
                    'area'=>$v['area'],//区域
                    'description'=>$v['description'],// 描述
                    'currency'=>$v['currency'],//币种
                    'name'=>$v['name'],//国家名称            
                    'countryid'=>$v['countryid'],//国家ID
                    'callingcode'=>$v['callingcode'],//国家区号代码
                    'chinaarea'=>$v['chinaarea'],//区域洲
                    'countrycode'=>$v['countrycode'],//国家代码
                    'vaild'=>$v['vaild'],//是否有效：1有效
                ];
            }
        }
         if($data){
          Db::name('country')->insertAll($data);
          return '数据插入成功';
        }else{
          return '数据插入失败'; 
        } 
    }


  
  ////产品尺寸转英文
    public  static function  getopenEn(){

          $redis = Cache::store('redis')->handler();    
       //查询那些图片是没有上传过的
        
        if( $redis->llen('openEn')==0){
          $result = Db::name('products')    
              ->whereOr([
                  ['option1_en','=', ''],
                  ['option2_en', '=', '']
              ])  
              ->where('pid','>',0)       
          ->column('id'); 
            $redis->lpush('openEn', ...$result);            
         }
        $product_id=$redis->rpop('openEn');
        if(empty($product_id)){
            echo '数据更新完成';
            exit;
        } 
          
        $product=Db::name('products')->where('id',$product_id)->find();
    
        if($product){
            $option1_en=isset($product['option1'])? self::youdao( $product['option1']) : ''  ;
            $option2_en=isset($product['option2'])? self::youdao( $product['option2']) : '';
            if($product=Db::name('products')->where('pid',$product['pid'])->where('option1_en',$option1_en)->find()){
                $option1_en= $option1_en.'-'.$option2_en;
            }

            $data['option1_en']=$option1_en;
            $data['option2_en']=$option2_en;
            Db::name('products')->where('id',$product_id)->update($data);
            return '数据更新成功';
        }else{
            return '数据更新失败';
        }
       
    }
    
    
    
    
    ////产品名称转英文
    public  static function  getnameEn(){

          $redis = Cache::store('redis')->handler();    
       //查询那些图片是没有上传过的
  
        if( $redis->llen('nameEn')==0){
          $result = Db::name('products')    
              ->where([
                  ['name_En','=', '']
              ])  
              ->where('pid','=',0)       
          ->column('id');  
         
            $redis->lpush('nameEn', ...$result);            
         }
        $product_id=$redis->rpop('nameEn');
        if(empty($product_id)){
            echo '数据更新完成';
            exit;
        } 
          
        $product=Db::name('products')->where('id',$product_id)->find();
          
        if($product){
            $data['name_En']=self::youdao($product['title']);
            Db::name('products')->whereor( [
                  ['id','=', $product_id],
                  ['pid','=', $product_id]
              ])->update($data);
           
            return '数据更新成功';
        }else{
            return '数据更新失败';
        }
       
    }
    
      //有道翻译为英文    
      public static  function youdao($title){

          $youdao=ConfigModel::where('code','youdao')->value('values');                  
          $youdao = json_decode($youdao,true);              
          $app_secret=$youdao['app_secret'];   
          $app_key=$youdao['app_key'];                  
          $q = $title;
          $from = "zh-CHS";
          $to = "en";   
          $params = array('q' => $q,
              'from' => $from,
              'to' => $to
              );
          $params = add_auth_params($params, $app_key,$app_secret);                 
          $r = do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
          $r = json_decode($r,true);
          if(isset($r['translation'])){
              return $r['translation'][0];
          }else{
              return $title;
          }
      }

      //产品尺寸自定义的图片
     public  static function  CustomImage( $accessToken,$shop_id=2){

          $redis = Cache::store('redis')->handler();    
       //查询那些图片是没有上传过的
      
        if( $redis->llen('CustomImage')==0){
          $result = Db::name('products')    
              ->where('dh_img','=','')  
              ->where('pid','>',0)       
          ->column('id');        
            $redis->lpush('CustomImage', ...$result);            
         }
         $product_id=$redis->rpop('CustomImage');
         if(empty($product_id)){
            echo '数据更新完成';
            exit;
        } 
         $method='dh.album.img.upload';//上传图片接口
         $product=Db::name('products')->where('id',$product_id)->find();
        if($product){
            $imageData = file_get_contents($product['img']);
                 $base64=base64_encode($imageData);                 
                 $sysParams = [
                    'method' => $method,
                    'v' => '2.0',
                    'access_token' => $accessToken,
                    'timestamp' => round(microtime(true) * 1000),
                    'funType' => 'albu',
                    'imageBase64' => $base64,
                    'imageBannerName' => '',
                    'imageName' => $product_id.'-'.$shop_id.'.jpg'
                 ];
                 $res=post_crul($sysParams);       
                 if($res['productImg']){
                      $img_url['l_imgurl']=$res['productImg']['l_imgurl'];
                      $img_url['l_imgmd5']=$res['productImg']['l_imgmd5'];
                      $img_url['l_localfilename']=$res['productImg']['l_localfilename'];
                      $img_url['l_imgsize']=$res['productImg']['l_imgsize'];
                 }  
                 $data['dh_img']=json_encode($img_url);      
                $re= Db::name('products')->where('id',$product_id)->update($data);
                 if($re){
                    return '数据更新成功';
                 }else{
                     return '数据更新失败';
                 }
           
        }else{
            return '数据更新失败';
        }
       
    }
    //dh.item.aftersale.list (获取售后模板列表接口)
    public  static function item_aftersale_list($accessToken,$shop_id){
        $method='dh.item.aftersale.list';
        $sysParams = [
          'method' => $method,
          'v' => '2.0',
          'access_token' => $accessToken,
          'timestamp' => round(microtime(true) * 1000),        
        ];   
         $data=[];    
        $res=crul($sysParams);
         if($res['afterSaleList']){
            foreach ($res['afterSaleList'] as  $v) {
                $data[]=[
                    'name'=>$v['name'],//售后模板名称
                     'shop_id'=>$shop_id,//店铺id
                    'freightBear'=>$v['freightBear'],//运费承担方 1：卖家 0:买家
                    'status'=>$v['status'],//是否已删除 0：已删除 1：未删除
                    'ifTemplateDefault'=>$v['ifTemplateDefault'],//货物描述不符和质量问题接受的保障期限 (天数)
                    'otherReturn'=>$v['otherReturn'],//其他原因
                    'afterSaleTemplateId'=>$v['afterSaleTemplateId'],//售后模板ID
                    'ifNoreasonBack'=>$v['ifNoreasonBack'],//是退货期限 3:3天退货 7:7天退货 15:15天退货
                    'returnRefund'=>$v['returnRefund'],//退货退款 1:退款保留货 10：买家支付运费 20：卖家支付运费
                    'createtime'=>date('Y-m-d H:i:s',strtotime($v['createDate'])),//创建日期
                ];
              }
              if($data){
                Db::name('aftersale_template')->insertAll($data);
                return '数据插入成功';
              }else{
                return '数据插入失败'; 
              }
         }
    }

    
}